//
//  ViewController.m
//  server100
//
//  Created by 孙晓晔 on 2017/5/15.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ViewController.h"
#import "MyServer.h"

@interface ViewController()
@property (weak) IBOutlet NSTextField *portText; // 端口
@property (weak) IBOutlet NSButton *startBtn; // 启动
@property (weak) IBOutlet NSButton *stopBtn; // 断开
@property (weak) IBOutlet NSButton *sendBtn;

@property (weak) IBOutlet NSTextField *inputText;

@property (weak) IBOutlet NSTextField *showText; // 显示状态
@property (weak) IBOutlet NSTextField *userText;

@property(nonatomic,strong) MyServer *server; // 服务

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:TRUE block:^(NSTimer * _Nonnull timer) {
        
        if (self.server.isOpen) {
            self.portText.enabled = FALSE;
            self.startBtn.enabled = FALSE;
            
            self.stopBtn.enabled = TRUE;
            self.sendBtn.enabled = TRUE;
        } else {
            self.portText.enabled = TRUE;
            self.startBtn.enabled = TRUE;
            
            self.stopBtn.enabled = FALSE;
            self.sendBtn.enabled = FALSE;
        }
        
        self.userText.stringValue = [self.server userList];
        self.showText.stringValue = [self.server msgList];
    }];
}

// 懒加载
-(MyServer *)server {
    if (_server == nil) {
        _server = [[MyServer alloc]initWithPort:[self.portText.stringValue intValue]];
    }
    
    return _server;
}

// 启动
- (IBAction)start:(id)sender {
    [self.server startListenAndNewThread];
}

// 停止
- (IBAction)stop:(id)sender {

    [self.server close];
}

// 群发消息
- (IBAction)send:(id)sender {
    NSLog(@"发送数据", nil);
    
    [self.server send:self.inputText.stringValue];
}

-(void)touchesBeganWithEvent:(NSEvent *)event {
    NSLog(@"touches");
    
    [self.inputText resignFirstResponder];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

@end
